<template>
  <div @click="tapMask" class="reader-container">
    <ReadHeaderBar class="header-bar"
                    @onBack="onBack"
                    @onHome="onHome"
                    @onCollect="onCollect">
                      <span>{{currentSections[currentSectionIndex].title}}</span>
                    </ReadHeaderBar>
    <!-- hear-bar end -->
    <!-- <div class="loadding"></div> -->
    <!-- swiper -->
    <swiper v-if="showSwiper"
            :class="[!isRollVertical?'my-swiper-horizontal':'my-swiper-vertical']"
            :options="options" 
            ref="mySwiper">
            <swiper-slide class="swiper-slide"
                v-for="(item, index) in content" ref="slide" id="slide">
                <img @load="loadImgEnd(index)" ref="img" v-lazy="item.image" alt="" style="">
              </swiper-slide>
            </swiper>
    <!-- swiper end -->

    <!-- 章节列表 -->
    <Scroll v-show="isShowSections"
          class="scroll-box"
          @onScroll="onScroll"
          ref="scroll"
          @click.stop="onStop">
            <ul class="comic-sections">
              <li v-for="item in currentSections" :key="item.sid" @click.stop="onTap(item.sid)">
                <Tag cname="cate-tag"><span>{{item.title}}</span></Tag>
              </li>
            </ul>
            <div class="scroll-close">
              <span class="btn-close" @click.self="onCloseSections">关闭</span>
            </div>
          </Scroll>
    

    <!-- <div class="download">上拉加载</div> -->
    <!-- download end -->
    <ReadMenuBar class="menu-bar"
                  @onSwitch="onSwitch"
                  @onPrevious="onPrevious"
                  @onNext="onNext"
                  @onCates="onCates"/>
    <!-- ReadMenuBar end -->
  </div>
</template>

<script>
import {swiper, swiperSlide} from 'vue-awesome-swiper'
import {getSections,getComicContent} from '../../api/comic.js'
import {Mixin} from '../../utils/mixin.js'
import Comic from '../common/Comic.vue'
import ReadHeaderBar from '../reader/ReadHeaderBar.vue'
import ReadMenuBar from '../reader/ReadMenuBar.vue'
import Scroll from '../core/scroll.vue'
import Tag from '../common/Tag.vue'

export default {
  mixins: [Mixin],
  components: {
    swiper,
    swiperSlide,
    Comic,
    ReadHeaderBar,
    ReadMenuBar,
    Scroll,
    Tag
  },
  data() {
    let self = this
    return {
      loadImgFirst: false,
      content: [],                //本章内容图片数据
      total: 0,                   //本章内容图片总计数
      currentSections: null,      //当前漫画的章节信息
      cid: -1, // 漫画id
      isShowSections: false,      //是否显示章节面板
      vertical: self.isRollVertical,
      showSwiper:true,            //控制Swiper显示
      currentSectionIndex: 0,     //当前阅读的章节进度
      options: {
          freeMode: false,
          setWrapperSize: true,
          autoHeight: false,
          mousewheelControl: true,
          initialSlide: self.currentReadProgress,
          on: {
            transitionStart(event) {
              self.$nextTick(()=>{
                self.setShowReadMenuBar(false)
                self.setShowReadHeaderBar(false)
                self.setCurrentReadProgress(self.$refs.mySwiper.swiper.activeIndex)
                console.log('total: '+self.total)
                console.log('progress: '+self.currentReadProgress)
                console.log('content length: '+self.content.length)
              })
            },
            reachEnd: function(event){
              self.$nextTick(()=>{
                if (self.$refs.mySwiper.swiper.activeIndex==self.content.length-1) {
                  self._loadContentPreviousOrNext('next',true)
                }
              })
            }
          }}
    }
  },
  created() {
    let params = this.$route.params
    if (!params){
      this.$router.go(-1)
    }
    try{
      params = {
        "cid": parseInt(params.cid),
        "sid": parseInt(params.sid)
      }
    }catch{
      this.$router.replace({path:'/404'})
    }
    this.setCurrentReadCID(params.cid)
    this._getComicContent(params)
    this._getSections()
    this.setShowReadMenuBar(false)
    this.setShowReadHeaderBar(false)
  },
  mounted() {
    
  },
  methods: {
    //根据图片高度动态设置swiper-slide高度
    loadImgEnd(index){
      this.$refs.mySwiper.$el.style.height = this.winHeight + 'px';
      this.$refs.img[index].style.height = this.winHeight + 'px';
      this.$refs.img[index].style.width = this.winWidth + 'px';
    },
    //切换横向纵向
    onSwitch() {
      console.log('未实现')
    },
    onScroll(pos) {
      
    },
    //加载章节内容数据
    _getComicContent(params,loop=false) {
      if (!params) {
        return
      }
      this.cid = params.cid
      
      const _this = this
      getComicContent(params)
        .then(
          res=>{
            console.log('loop = '+loop)
            if (loop) {
              _this.content = _this.content.push(...res.images)
              _this.total += res.total
            }else{
              _this.content = res.images
              _this.total = res.total
              _this.setCurrentReadProgress(0)
              _this.mySlideTo(this.currentReadProgress)              
            }
            _this.setCurrentReadSID(params.sid)
            _this.currentSectionIndex = this.currentSections.findIndex(item=>item.sid==params.sid)
            _this.$router.replace({
              path: `/comic/${this.cid}/${params.sid}`
            })
          },err=>{
          console.log(err)
        })
    },
    //加载章节内容数据
    _getSections() {
      console.log('1 '+this.cid)
      if(this.cid==this.currentReadCID) {
        console.log('1')
        this.currentSections = this.currentReadSections
      }else {
        getSections(this.cid)
          .then(res=>{
            console.log('2')
            this.setCurrentReadSections(res.sections)
          })
      }
    },
    //加载上一章或下一章内容
    _loadContentPreviousOrNext(previousOrNext='next',loop=false) {
      let params = null
      const currentSectionIndex = this.currentSectionIndex||this.currentSections.findIndex(item=>item.sid==this.currentReadSID)
      if (previousOrNext=='next') {
        //下一章内容
        params = {
          "cid": this.cid,
          "sid": this.currentSections[currentSectionIndex+1].sid
        }
      }
      if (previousOrNext=='previous') {
        if(currentSectionIndex==0){
          console.log('没有上一章了')
          return
        }
        //上一章内容
        params = {
          "cid": this.cid,
          "sid": this.currentSections[currentSectionIndex-1].sid
        }
      }
      //加载
      if(loop===false){this.content = []}
      this._getComicContent(params,loop)
    },
    //回滚到
    mySlideTo(index) {
      this.$refs.mySwiper.swiper.slideTo(index, 500, false)
    },
    //点击遮罩弹出控制面板
    tapMask() {
      if (this.isShowSections==true) {return}
      this.onReaderCtrPanel()
    },
    // 回到上一路由
    onBack() {
      this.$router.go(-1)
    },
    // 回到主页
    onHome() {
      this.$router.push({path: '/'})
    },
    // 点击上一章按钮
    onPrevious() {
      this._loadContentPreviousOrNext('previous',false)
    },
    // 点击下一章按钮
    onNext() {
      this._loadContentPreviousOrNext('next',false)
    },
    // 点击展开目录
    onCates() {
      this.isShowSections = true
    },
    // 点击关闭目录
    onCloseSections() {
      this.isShowSections = false
    },
    // 点击章节标签
    onTap(sid) {
      if(!sid) {return}
      let params={
        "cid":this.cid,
        "sid":sid
      }
      this.content = []
      this._getComicContent(params, false)
      this.onCloseSections()
    },
    // 回到收藏页
    onCollect() {

    },
    beforeDestroy() {
      this.setShowReadMenuBar(false)
      this.setShowReadHeaderBar(false)
    }
  }
}
</script>
<style lang="scss" scoped>
@import "~swiper/dist/css/swiper.css";
@import '../../assets/style/color.scss';
@import '../../assets/style/mixin.scss';

.reader-container {
  width: 100%;
  background-color: #fff;
  .header-bar {
    position: fixed;
    left: 0;
    top: 0;
    z-index: 150;
    span {
      color: $color-text-f;
    }
  }
  .menu-bar {
    position: fixed;
    left: 0;
    bottom: 0;
    z-index: 150;
  }
  
  .scroll-box {
    position: absolute;
    bottom: 100px;
    z-index: 157;
    width: 100%;
    background-color: $color-bg-mask-7;
    padding-top: 150px;
    padding-bottom: 10px;
    .scroll-close {
      width: 100%;
      height: 100px;
      position: fixed;
      bottom: 0;
      z-index: 159;
      box-sizing: border-box;
      background-color: $color-bg-mask-7;
      pointer-events: auto;
      @include center;
      .btn-close {
        width: 72px;
        height: 36px;
        color: $color-text-f;
        @include center;
        background: $color-text-7;
        border-radius: 16px;
        pointer-events: auto;
      }
    }
    .comic-sections {
      width: 100%;
      margin: auto;
      display: flex;
      justify-content: flex-start;
      align-items: flex-start;
      flex-wrap: wrap;
      padding: 0 10px;
      color: $color-text-9;
      overflow: hidden;
      li {
        width: 22%;
        height: 30px;
        line-height: 30px;
        margin-top: 8px;
        margin-right: 3%;
        text-align: center;
        background-color: $color-bg-mask;
        box-sizing: border-box;
        border:1px solid $color-text-7;
        border-radius: 2px;
        font-size: $font-size-14;
        overflow: hidden;
        .cate-tag {
          box-sizing: border-box;
          padding: 1px 6px 3px 6px;
        }
      }
    }
  }

}
</style>
